# -*- coding = utf-8 -*-
# @Time：2022/3/14 13:01
# @Author：3ic
# @File：stop_watch.py.py
# @Software：PyCharm

import threading
import time

from PyQt5.QtCore import Qt
from PyQt5.QtWidgets import QLineEdit


class StopWatch(QLineEdit):
    def __init__(self, parent_window=None, x=0, y=0):
        QLineEdit.__init__(self, parent_window)
        self.setText("-:-(-)")
        self.setAlignment(Qt.AlignCenter)
        self.resize(130, 40)
        self.setReadOnly(True)
        self.setStyleSheet('font-size:18px;font-weight:700;border:0;background-color:#FFB6C1;')
        self.setParent(parent_window)
        self.move(x, y)

        self._display_thread = None
        self._allow_working = False

    def _displaySec(self, sec_msg_pipe):
        while self._allow_working:
            if sec_msg_pipe.poll():
                (sec, frame_cnt) = sec_msg_pipe.recv()
                if sec == -1:
                    break
                sec_str = '1:' if sec >= 60 else '0:'
                sec_str += str(sec - 60 if sec >= 60 else sec).zfill(2)
                if frame_cnt == -1:
                    sec_str += '未执行'
                else:
                    sec_str += '(' + str(frame_cnt) + ')'
                self.setText(sec_str)
            time.sleep(0.1)

    def start(self, sec_msg_pipe):
        self._allow_working = True
        self._display_thread = threading.Thread(target=self._displaySec, args=(sec_msg_pipe,))
        self._display_thread.start()

    def terminate(self):
        self._allow_working = False
        self._display_thread.join()
        self._display_thread = None
